<template>
  <div class="app-container">
    <div class="head-container">
      <div style="margin-bottom: 5px">
        <el-input class="input" size="small" style="width:200px" v-model="listQuery.moduleName" placeholder="请输入模块名称"
                  clearable></el-input>
        <el-button
          type="success"
          icon="el-icon-search"
          size="mini"
          @click="getTablePage(true)"
        >
          查询
        </el-button>
        <el-button
          style="margin-left: 10px"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="openDialogTableForm(false)"
        >新增
        </el-button>
      </div>
      <el-table
        ref="genTable"
        v-loading="listLoading"
        :data="list"
        border
        fit
        style="width: 100%;"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"/>
        <el-table-column type="index" width="50" label="序号">
          <template slot-scope="scope">
            <span>{{listQuery.pageNo * listQuery.pageSize +scope.row.listIndex + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="moduleName" label="模块名称" min-width="120"/>
        <el-table-column prop="tableName" label="数据库表名" min-width="120"/>
        <el-table-column prop="formDesc" label="表单描述" min-width="120"/>
        <el-table-column prop="menuName" label="菜单名称" min-width="120"/>
        <el-table-column prop="path" label="请求路径" min-width="120"/>
        <el-table-column prop="createTime" label="创建时间" min-width="120"/>
        <el-table-column prop="menuStatus" label="菜单状态" min-width="50">
          <template slot-scope="scope">
            <el-switch
              @change=handleDynamicMenu(scope.row)
              v-model="scope.row.menuStatus"
              active-value="show"
              inactive-value="hidden"
            >
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column align="left" label="操作" min-width="280">
          <template slot-scope="scope">
            <el-button style="margin-left: 10px" type="primary" size="mini" @click="handleViewField(scope.row)">设计表单详情
            </el-button>

            <el-button style="margin-left: 10px" type="success" size="mini"
                       @click="openDialogTableForm(true,scope.row)">
              修改
            </el-button>
            <el-button style="margin-left: 10px" type="danger" size="mini" @click="handleDelete(scope.row)">删除
            </el-button>
            <el-button style="margin-left: 10px" type="warning" size="mini" @click="handleDelete(scope.row)">表单设计
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <el-pagination
        style="margin-top: 8px;"
        layout="total, prev, pager, next"
        :page-size="listQuery.pageSize"
        :total="total"
        prev-text="上一页"
        next-text="下一页"
        :current-page="listQuery.pageNo+1"
        @current-change="paginationChange"
      >
      </el-pagination>
      <!-- 弹出框新增table -->
      <el-dialog title="模块菜单信息" :visible.sync="dialogTableFormVisible">
        <el-form
          ref="tableForm"
          :model="tableForm"
          :rules="rules"
          label-position="right"
          style="width: 740px; margin-left:20px; margin-right: 0px;"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="模块名称" prop="moduleName" label-width="120px">
                <el-input v-model="tableForm.moduleName" maxlength="60" style="width:220px;"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数据库表名" prop="tableName" label-width="120px">
                <el-select v-model="tableForm.tableName" clearable filterable style="width:280px;">
                  <el-option v-for="item in selectList.tableList " :key="item" :label="item" :value="item">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="表单描述" prop="formDesc" label-width="120px">
                <el-input v-model="tableForm.formDesc" maxlength="60" style="width:220px;"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="关联流程" prop="workflow" label-width="120px">
                <div style="width: 280px">
                  <page-select
                    labelKey="name"
                    style="width: 100%"
                    valueKey="procDefName"
                    v-model="tableForm.procDefName"
                    :url="selectUrl"
                    @change="change"
                  />
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="菜单名称" prop="menuName" label-width="120px">
                <el-input v-model="tableForm.menuName" maxlength="60" style="width:220px;"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="菜单编码" prop="menuCode" label-width="120px">
                <el-input v-model="tableForm.menuCode" maxlength="60" style="width:280px;"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="路由地址" prop="path" label-width="120px">
                <el-input v-model="tableForm.path" maxlength="60" style="width:220px;"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="上级菜单" label-width="120px" prop="pcode">
                <treeselect
                  v-model="tableForm.pcode"
                  :options="menus"
                  :normalizer="normalizer"
                  style="width: 280px;"
                  placeholder="选择上级"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer" align="center">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="saveTable">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import {add, edit, del, tableList, getMenusTree, getTablePage} from '@/api/system/moduleform'
  import msgUtil from '@/utils/msgUtil'
  import PageSelect from '@/components/PageSelect'
  import {url} from '@/api/wf/modeler'
  import store from '@/store'

  // 定义table 的表单
  const tableForm = {
    id: '',
    moduleName: '',
    tableName: '',
    formDesc: '',
    menuCode: '',
    menuName: '',
    path: '',
    pcode: '',
    procDefName: '',
    menuStatus: 'hidden'
  }
  export default {
    components: { PageSelect},
    data() {
      return {
        menus: [],
        isEdit: false,
        tableForm: tableForm,
        dialogTableFormVisible: false, // 弹出的新增修改表单窗口
        selTableId: 0, // 选中行的tableId
        selType: 0, // 选中的创建文件类型
        tableKey: 0,
        list: null,
        listLoading: false,
        total: 0,
        selectUrl: url.getPage,
        listQuery: {
          pageNo: 0,
          pageSize: 10,
          condition: '',
          moduleName: '',
        },
        selectList: {
          tableList: [],
        },
        rules: {
          moduleName: [{required: true, trigger: 'blur', message: '模块名不能为空'}],
          formDesc: [{required: true, trigger: 'blur', message: '表单描述不能为空'}],
          menuName: [{required: true, trigger: 'blur', message: '菜单名称不能为空'}],
          menuCode: [{required: true, trigger: 'blur', message: '菜单编号不能为空'}],
          path: [{required: true, trigger: 'blur', message: '请输入请求路由地址'}],
          pcode: [{required: true, trigger: 'blur', message: '请选择上级菜单'}],
        }
      }
    },
    created() {
      this.getTablePage()
      this.getTableList()
      this.getMenusTree()
    },
    methods: {
      change(val) {
        this.tableForm.procDefName = val
      },
      paginationChange(index) {
        this.listQuery.pageNo = index
        this.getTablePage()
      },
      getMenusTree() {
        let param = {type: 0}
        getMenusTree(param).then(res => {
          this.menus = res.data
        }).catch((response) => {
        })
      },
      normalizer(node) {
        if (!node.data) {
          node.data = {
            code: '0',
            name: '请选择菜单'
          }
        }
        if (node.children == null || !node.children.length) {
          delete node.children
        }
        return {
          id: node.data.code,
          label: node.data.name,
          children: node.children
        }
      },
      getTableList() {
        tableList().then(res => {
          this.selectList.tableList = res.data
        }).catch((response) => {
        })
      },
      cancel() {
        this.dialogTableFormVisible = false
        this.fieldForm = {
          id: null,
          moduleName: '',
          tableName: '',
          formDesc: '',
          menuCode: '',
          menuName: '',
          path: '',
          pcode: '',
        }

      },
      // 保存数据表配置
      saveTable() {
        this.$refs.tableForm.validate(valid => {
          if (valid) {
            if (this.tableForm.path.substring(0, 1).indexOf('/') !== -1) {
              //有斜杠则自动去掉
              this.tableForm.path = this.tableForm.path.substring(1);
            }
            if (this.isEdit) {
              edit(this.tableForm).then(response => {
                this.dialogTableFormVisible = false
                this.$notify({
                  title: '数据表修改成功',
                  type: 'success',
                  duration: 1500
                })
                this.getTablePage()
              })
            } else {
              add(this.tableForm).then(response => {
                this.dialogTableFormVisible = false
                this.$notify({
                  title: '数据表添加成功',
                  type: 'success',
                  duration: 1500
                })
                this.getTablePage()
                this.cancel()
              })
            }
          }
        })
      },
      // 删除
      handleDelete(row) {
        msgUtil.confirm('确认删除表数据?').then(async () => {
          const ids = []
          ids.push(row.id)
          await del(ids)
          msgUtil.success2('删除成功!')
          this.getTablePage()
        })
      },
      getTablePage(reload) {
        if (reload) {
          this.listQuery.pageNo = 0
        }
        this.listLoading = true
        getTablePage(this.listQuery).then(res => {
          this.list = res.data.content
          this.total = res.data.totalElements
          res.data.content.forEach((item, index) => {
            item.listIndex = index
          });
          this.$nextTick(() => {
            this.listLoading = false
          })
        })
      },
      handleSelectionChange(val) {
        if (val.length > 1) {
          this.$refs.genTable.clearSelection()
          this.$refs.genTable.toggleRowSelection(val[val.length - 1])
        } else if (val.length === 0) {
          this.selTableId = 0
        } else {
          this.multipleSelection = val[val.length - 1]
          this.selTableId = val[0].id
        }
      },
      // 打开tableform窗口
      openDialogTableForm(isEdit, row) {
        this.isEdit = isEdit
        if (isEdit) {
          this.tableForm = row
          this.dialogTableFormVisible = true
        } else {
          this.dialogTableFormVisible = true
          this.tableForm = {
            id: '',
            tableName: '',
            tableNameDesc: '',
            modelName: '',
            authorName: '',
            javaPackage: ''
          }
        }
      },
      // 查看字段明细
      handleViewField(row) {
        this.$router.push({
          path: 'form/formindex',
          query: {moduleFormId: row.id}
        })
      },
      // 启用菜单
      handleDynamicMenu(row) {
        this.tableForm = row
        edit(this.tableForm).then(response => {
        })
        msgUtil.confirm('是否重新登陆加载菜单?').then(async () => {
          store.dispatch('LogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        })
      },

    }
  }
</script>
